<template>
  <div class="queue-management">
    <div class="header">
      <h1>用户队列管理</h1>
      <p>管理当前正在排队的用户申请</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.pending_users || 0 }}</div>
                <div class="stat-label">待确认用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon confirmed">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.confirmed_users || 0 }}</div>
                <div class="stat-label">已确认用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.total_users || 0 }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon time">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ formatWaitingTime(stats.average_waiting_time) }}</div>
                <div class="stat-label">平均等待时间(分钟)</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>


    <!-- 操作按钮 -->
    <div class="actions-section">
      <el-button type="primary" @click="refreshData" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
      <el-button type="warning" @click="showCleanupDialog">
        <el-icon><Delete /></el-icon>
        清理过期请求
      </el-button>
      <el-button type="info" @click="exportData">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 数据图表 -->
      <el-tab-pane label="数据图表" name="dashboard">
        <div class="dashboard-content">
          <!-- 概览卡片 -->
          <div class="overview-cards">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="card-content">
                    <div class="card-icon total">
                      <el-icon><Document /></el-icon>
                    </div>
                    <div class="card-info">
                      <div class="card-title">总请求数</div>
                      <div class="card-value">{{ dashboardData.overview?.total_requests || 0 }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="card-content">
                    <div class="card-icon pending">
                      <el-icon><Clock /></el-icon>
                    </div>
                    <div class="card-info">
                      <div class="card-title">待确认</div>
                      <div class="card-value">{{ dashboardData.overview?.pending_count || 0 }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="card-content">
                    <div class="card-icon confirmed">
                      <el-icon><Check /></el-icon>
                    </div>
                    <div class="card-info">
                      <div class="card-title">已确认</div>
                      <div class="card-value">{{ dashboardData.overview?.confirmed_count || 0 }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="overview-card">
                  <div class="card-content">
                    <div class="card-icon success">
                      <el-icon><TrendCharts /></el-icon>
                    </div>
                    <div class="card-info">
                      <div class="card-title">成功率</div>
                      <div class="card-value">{{ dashboardData.overview?.success_rate || 0 }}%</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 图表区域 -->
          <div class="charts-section">
            <el-row :gutter="20">
              <!-- 状态分布饼图 -->
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>状态分布</span>
                      <el-icon><PieChart /></el-icon>
                    </div>
                  </template>
                  <div class="chart-container">
                    <div ref="statusChart" class="chart"></div>
                  </div>
                </el-card>
              </el-col>

              <!-- 服务类型分布饼图 -->
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>服务类型分布</span>
                      <el-icon><PieChart /></el-icon>
                    </div>
                  </template>
                  <div class="chart-container">
                    <div ref="serviceChart" class="chart"></div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 20px;">
              <!-- 每日趋势图 -->
              <el-col :span="24">
                <el-card class="chart-card">
                  <template #header>
                    <div class="card-header">
                      <span>每日请求趋势（最近7天）</span>
                      <el-icon><TrendCharts /></el-icon>
                    </div>
                  </template>
                  <div class="chart-container">
                    <div ref="trendChart" class="chart trend-chart"></div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 数据更新时间 -->
          <div class="update-time">
            <el-text type="info" size="small">
              最后更新: {{ formatUpdateTime(dashboardData.last_updated) }}
            </el-text>
          </div>
        </div>
      </el-tab-pane>
      
      <!-- 待确认用户 -->
      <el-tab-pane label="待确认用户" name="pending">
        <el-table :data="pendingUsers" v-loading="loading" stripe>
          <el-table-column prop="name" label="姓名" width="150" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="service" label="服务类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getServiceTagType(row.service)">{{ row.service }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="submitted_at" label="提交时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.submitted_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="waiting_time" label="等待时间" width="120">
            <template #default="{ row }">
              <el-tag :type="getWaitingTimeTagType(row.waiting_time)">
                {{ row.waiting_time }}分钟
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="viewUserDetails(row.request_id)">
                查看详情
              </el-button>
              <el-button size="small" type="danger" @click="removeUser(row.request_id)">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 已确认用户 -->
      <el-tab-pane label="已确认用户" name="confirmed">
        <el-table :data="confirmedUsers" v-loading="loading" stripe>
          <el-table-column prop="name" label="姓名" width="150" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="service" label="服务类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getServiceTagType(row.service)">{{ row.service }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="confirmed_at" label="确认时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.confirmed_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="processing_time" label="处理时间" width="120">
            <template #default="{ row }">
              {{ row.processing_time }}分钟
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <el-button size="small" @click="viewUserDetails(row.request_id)">
                查看详情
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="removeUser(row.request_id)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 统计信息 -->
      <el-tab-pane label="统计信息" name="statistics">
        <div class="statistics-content">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <el-icon><PieChart /></el-icon>
                    <span>服务类型分布</span>
                  </div>
                </template>
                <div class="service-stats">
                  <div v-for="(service, name) in stats.service_statistics" :key="name" class="service-item">
                    <div class="service-name">{{ name }}</div>
                    <div class="service-counts">
                      <span class="pending-count">待确认: {{ service.pending }}</span>
                      <span class="confirmed-count">已确认: {{ service.confirmed }}</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <el-icon><TrendCharts /></el-icon>
                    <span>队列性能</span>
                  </div>
                </template>
                <div class="performance-stats">
                  <div class="performance-item">
                    <div class="performance-label">平均等待时间</div>
                    <div class="performance-value">{{ formatWaitingTime(stats.average_waiting_time) }}分钟</div>
                  </div>
                  <div class="performance-item">
                    <div class="performance-label">总用户数</div>
                    <div class="performance-value">{{ stats.total_users }}</div>
                  </div>
                  <div class="performance-item">
                    <div class="performance-label">确认率</div>
                    <div class="performance-value">
                      {{ stats.total_users > 0 ? Math.round((stats.confirmed_users / stats.total_users) * 100) : 0 }}%
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="userDetailsVisible" title="用户详细信息" width="800px">
      <div v-if="currentUserDetails" class="user-details">
        <!-- 用户基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请ID">
            {{ currentUserDetails.request_id }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentUserDetails.status)">
              {{ getStatusText(currentUserDetails.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="称呼">
            {{ currentUserDetails.anrede }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ currentUserDetails.first_name }} {{ currentUserDetails.last_name }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ currentUserDetails.email }}
          </el-descriptions-item>
          <el-descriptions-item label="电话">
            {{ currentUserDetails.phone || '未提供' }}
          </el-descriptions-item>
          <el-descriptions-item label="生日">
            {{ currentUserDetails.birthday }}
          </el-descriptions-item>
          <el-descriptions-item label="服务类型">
            <el-tag :type="getServiceTagType(currentUserDetails.service)">
              {{ currentUserDetails.service }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地址">
            {{ currentUserDetails.address || '未提供' }}
          </el-descriptions-item>
          <el-descriptions-item label="邮编">
            {{ currentUserDetails.zip_code || '未提供' }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ formatDateTime(currentUserDetails.submitted_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="确认时间" v-if="currentUserDetails.confirmed_at">
            {{ formatDateTime(currentUserDetails.confirmed_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 用户日志部分 -->
        <div class="logs-section">
          <div class="logs-header">
            <h3>用户日志</h3>
            <div class="logs-actions">
              <el-button size="small" @click="refreshLogs" :loading="logsLoading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <el-button size="small" @click="toggleAutoRefresh" :type="autoRefresh ? 'primary' : 'default'">
                <el-icon><Timer /></el-icon>
                {{ autoRefresh ? '停止自动刷新' : '自动刷新' }}
              </el-button>
            </div>
          </div>
          
          <div class="logs-content">
            <div v-if="logsLoading" class="logs-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            <div v-else-if="userLogs.length === 0" class="logs-empty">
              <span>暂无日志记录</span>
            </div>
            <div v-else class="logs-table-container">
              <el-table 
                :data="userLogs" 
                size="small" 
                stripe
                :show-header="false"
                max-height="400"
                class="logs-table"
              >
                <el-table-column prop="content" label="日志内容">
                  <template #default="{ row, $index }">
                    <div class="log-row">
                      <span class="log-index">{{ $index + 1 }}</span>
                      <span class="log-text">{{ row }}</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 清理过期请求对话框 -->
    <el-dialog v-model="cleanupDialogVisible" title="清理过期请求" width="400px">
      <div class="cleanup-content">
        <p>清理超过指定时间的未确认请求</p>
        <el-form :model="cleanupForm">
          <el-form-item label="过期时间">
            <el-select v-model="cleanupForm.hours" placeholder="选择过期时间">
              <el-option label="1小时" :value="1" />
              <el-option label="6小时" :value="6" />
              <el-option label="12小时" :value="12" />
              <el-option label="24小时" :value="24" />
              <el-option label="48小时" :value="48" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="cleanupDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="cleanupExpiredRequests" :loading="cleanupLoading">
          确认清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Clock, Check, User, Timer, Refresh, Delete, Download, 
  PieChart, TrendCharts, Loading, Document
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import api from '../utils/api'

export default {
  name: 'QueueManagement',
  components: {
    Clock, Check, User, Timer, Refresh, Delete, Download,
    PieChart, TrendCharts, Loading, Document
  },
  setup() {
    const loading = ref(false)
    const activeTab = ref('pending')
    const userDetailsVisible = ref(false)
    const cleanupDialogVisible = ref(false)
    const cleanupLoading = ref(false)
    
    const stats = ref({})
    const pendingUsers = ref([])
    const confirmedUsers = ref([])
    const currentUserDetails = ref(null)
    
    // 日志相关状态
    const userLogs = ref([])
    const logsLoading = ref(false)
    const autoRefresh = ref(false)
    const autoRefreshTimer = ref(null)
    
    // Dashboard相关状态
    const dashboardData = reactive({
      overview: {},
      status_distribution: {},
      service_distribution: {},
      daily_trend: {},
      last_updated: null
    })

    // 图表实例
    const statusChart = ref(null)
    const serviceChart = ref(null)
    const trendChart = ref(null)
    let statusChartInstance = null
    let serviceChartInstance = null
    let trendChartInstance = null
    
    const cleanupForm = reactive({
      hours: 24
    })

    // 获取队列状态
    const getQueueStatus = async (silent = false) => {
      try {
        const response = await api.getQueueStatus()
        if (response.data.success) {
          stats.value = response.data.data
        }
      } catch (error) {
        console.error('获取队列状态失败:', error)
        if (!silent) {
          ElMessage.error('获取队列状态失败')
        }
      }
    }

    // 获取待确认用户
    const getPendingUsers = async (silent = false) => {
      try {
        const response = await api.getPendingUsers()
        if (response.data.success) {
          pendingUsers.value = response.data.data
        }
      } catch (error) {
        console.error('获取待确认用户失败:', error)
        if (!silent) {
          ElMessage.error('获取待确认用户失败')
        }
      }
    }

    // 获取已确认用户
    const getConfirmedUsers = async (silent = false) => {
      try {
        const response = await api.getConfirmedUsers()
        if (response.data.success) {
          confirmedUsers.value = response.data.data
        }
      } catch (error) {
        console.error('获取已确认用户失败:', error)
        if (!silent) {
          ElMessage.error('获取已确认用户失败')
        }
      }
    }

    // 获取统计信息
    const getStatistics = async (silent = false) => {
      try {
        const response = await api.getQueueStatistics()
        if (response.data.success) {
          stats.value = { ...stats.value, ...response.data.data }
        }
      } catch (error) {
        console.error('获取统计信息失败:', error)
        if (!silent) {
          ElMessage.error('获取统计信息失败')
        }
      }
    }

    // 刷新数据
    const refreshData = async () => {
      loading.value = true
      try {
        await Promise.all([
          getQueueStatus(),
          getPendingUsers(),
          getConfirmedUsers(),
          getStatistics(),
          getDashboardData()
        ])
        ElMessage.success('数据刷新成功')
      } catch (error) {
        ElMessage.error('数据刷新失败')
      } finally {
        loading.value = false
      }
    }

    // 查看用户详情
    const viewUserDetails = async (requestId) => {
      try {
        const response = await api.getUserDetails(requestId)
        if (response.data.success) {
          currentUserDetails.value = response.data.data
          userDetailsVisible.value = true
          // 自动加载用户日志
          await loadUserLogs(requestId)
        } else {
          ElMessage.error('获取用户详情失败')
        }
      } catch (error) {
        ElMessage.error('获取用户详情失败')
      }
    }

    // 加载用户日志
    const loadUserLogs = async (requestId, silent = false) => {
      if (!silent) {
        logsLoading.value = true
      }
      try {
        const response = await api.getUserLogs(requestId)
        if (response.data.success) {
          userLogs.value = response.data.logs || []
        } else {
          if (!silent) {
            ElMessage.error('获取用户日志失败')
          }
          userLogs.value = []
        }
      } catch (error) {
        console.error('获取用户日志失败:', error)
        if (!silent) {
          ElMessage.error('获取用户日志失败')
        }
        userLogs.value = []
      } finally {
        if (!silent) {
          logsLoading.value = false
        }
      }
    }

    // 刷新日志
    const refreshLogs = async () => {
      if (currentUserDetails.value) {
        await loadUserLogs(currentUserDetails.value.request_id)
      }
    }






    // 异步刷新数据（不显示加载状态）
    const silentRefreshData = async () => {
      try {
        await Promise.all([
          getQueueStatus(true),  // 静默模式
          getPendingUsers(true), // 静默模式
          getConfirmedUsers(true), // 静默模式
          getStatistics(true),   // 静默模式
          getDashboardData(true) // 静默模式
        ])
        // 如果用户详情对话框打开，也刷新日志
        if (currentUserDetails.value && userDetailsVisible.value) {
          await loadUserLogs(currentUserDetails.value.request_id, true) // 静默模式
        }
      } catch (error) {
        console.error('自动刷新数据失败:', error)
        // 静默失败，不显示错误消息
      }
    }

    // Dashboard相关方法
    // 获取仪表板数据
    const getDashboardData = async (silent = false) => {
      try {
        const response = await api.getDashboardData()
        if (response.data.success) {
          Object.assign(dashboardData, response.data.data)
          await nextTick()
          if (activeTab.value === 'dashboard') {
            // 确保图表已初始化
            if (!statusChartInstance || !serviceChartInstance || !trendChartInstance) {
              setTimeout(() => {
                initCharts()
                updateCharts()
              }, 100)
            } else {
              updateCharts()
            }
          }
        } else {
          if (!silent) {
            ElMessage.error(response.data.error || '获取仪表板数据失败')
          }
        }
      } catch (error) {
        if (!silent) {
          console.error('获取仪表板数据失败:', error)
          ElMessage.error('获取仪表板数据失败')
        }
      }
    }

    // 初始化图表
    const initCharts = () => {
      try {
        // 状态分布饼图
        if (statusChart.value && !statusChartInstance) {
          statusChartInstance = echarts.init(statusChart.value)
          console.log('状态分布饼图初始化成功')
        }
        
        // 服务类型分布饼图
        if (serviceChart.value && !serviceChartInstance) {
          serviceChartInstance = echarts.init(serviceChart.value)
          console.log('服务类型分布饼图初始化成功')
        }
        
        // 趋势图
        if (trendChart.value && !trendChartInstance) {
          trendChartInstance = echarts.init(trendChart.value)
          console.log('趋势图初始化成功')
        }
      } catch (error) {
        console.error('图表初始化失败:', error)
      }
    }

    // 更新图表
    const updateCharts = () => {
      updateStatusChart()
      updateServiceChart()
      updateTrendChart()
    }

    // 更新状态分布饼图
    const updateStatusChart = () => {
      if (!statusChartInstance) return

      const statusData = dashboardData.status_distribution || {}
      const data = Object.entries(statusData).map(([key, value]) => ({
        name: getStatusText(key),
        value: value
      })).filter(item => item.value > 0)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center'
        },
        series: [
          {
            name: '状态分布',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ],
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#9C27B0']
      }

      statusChartInstance.setOption(option)
    }

    // 更新服务类型分布饼图
    const updateServiceChart = () => {
      if (!serviceChartInstance) return

      const serviceData = dashboardData.service_distribution || {}
      const data = Object.entries(serviceData).map(([key, value]) => ({
        name: key,
        value: value
      })).filter(item => item.value > 0)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center'
        },
        series: [
          {
            name: '服务类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data
          }
        ],
        color: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
      }

      serviceChartInstance.setOption(option)
    }

    // 更新趋势图
    const updateTrendChart = () => {
      if (!trendChartInstance) return

      const trendData = dashboardData.daily_trend || {}
      const dates = Object.keys(trendData).sort()
      const values = dates.map(date => trendData[date])

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates.map(date => {
            const d = new Date(date)
            return `${d.getMonth() + 1}/${d.getDate()}`
          })
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [
          {
            name: '请求数量',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#409EFF',
              width: 3
            },
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(64, 158, 255, 0.3)'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                }]
              }
            },
            data: values
          }
        ]
      }

      trendChartInstance.setOption(option)
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'processing': '处理中',
        'completed': '已完成',
        'failed': '失败',
        'error': '错误'
      }
      return statusMap[status] || status
    }

    // 格式化更新时间
    const formatUpdateTime = (timeStr) => {
      if (!timeStr) return '未知'
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN')
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (statusChartInstance) statusChartInstance.resize()
      if (serviceChartInstance) serviceChartInstance.resize()
      if (trendChartInstance) trendChartInstance.resize()
    }

    // 切换自动刷新
    const toggleAutoRefresh = () => {
      autoRefresh.value = !autoRefresh.value
      if (autoRefresh.value) {
        // 开始自动刷新，每10秒刷新一次数据
        autoRefreshTimer.value = setInterval(() => {
          silentRefreshData()
        }, 10000)
        ElMessage.success('已开启自动刷新（每10秒）')
      } else {
        // 停止自动刷新
        if (autoRefreshTimer.value) {
          clearInterval(autoRefreshTimer.value)
          autoRefreshTimer.value = null
        }
        ElMessage.info('已停止自动刷新')
      }
    }


    // 移除用户
    const removeUser = async (requestId) => {
      try {
        await ElMessageBox.confirm('确定要移除这个用户吗？', '确认移除', {
          type: 'warning'
        })
        
        const response = await api.removeUser(requestId)
        if (response.data.success) {
          ElMessage.success('用户移除成功')
          refreshData()
        } else {
          ElMessage.error('用户移除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('用户移除失败')
        }
      }
    }

    // 清理过期请求
    const cleanupExpiredRequests = async () => {
      cleanupLoading.value = true
      try {
        const response = await api.cleanupExpiredRequests(cleanupForm.hours)
        if (response.data.success) {
          ElMessage.success(response.data.message)
          cleanupDialogVisible.value = false
          refreshData()
        } else {
          ElMessage.error('清理失败')
        }
      } catch (error) {
        ElMessage.error('清理失败')
      } finally {
        cleanupLoading.value = false
      }
    }

    // 显示清理对话框
    const showCleanupDialog = () => {
      cleanupDialogVisible.value = true
    }

    // 导出数据
    const exportData = () => {
      const data = {
        stats: stats.value,
        pendingUsers: pendingUsers.value,
        confirmedUsers: confirmedUsers.value,
        exportTime: new Date().toISOString()
      }
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `queue_data_${new Date().toISOString().split('T')[0]}.json`
      a.click()
      URL.revokeObjectURL(url)
      
      ElMessage.success('数据导出成功')
    }

    // 标签页切换
    const handleTabClick = (tab) => {
      if (tab.name === 'statistics') {
        getStatistics()
      } else if (tab.name === 'dashboard') {
        // 切换到Dashboard标签页时初始化图表
        nextTick(() => {
          // 延迟初始化，确保DOM完全渲染
          setTimeout(() => {
            initCharts()
            updateCharts()
          }, 300)
        })
      }
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    // 格式化等待时间
    const formatWaitingTime = (time) => {
      if (!time && time !== 0) return '0'
      return typeof time === 'number' ? time.toFixed(1) : time
    }

    // 获取服务类型标签类型
    const getServiceTagType = (service) => {
      const types = {
        '学生签': 'success',
        '工作签': 'warning',
        '家庭团聚': 'info',
        '旅游签': 'primary'
      }
      return types[service] || 'default'
    }

    // 获取等待时间标签类型
    const getWaitingTimeTagType = (time) => {
      if (time < 30) return 'success'
      if (time < 60) return 'warning'
      return 'danger'
    }

    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const types = {
        'pending': 'warning',
        'confirmed': 'info',
        'completed': 'success',
        'failed': 'danger'
      }
      return types[status] || 'default'
    }


    onMounted(async () => {
      await refreshData()
      window.addEventListener('resize', handleResize)
    })

    onUnmounted(() => {
      // 清理自动刷新定时器
      if (autoRefreshTimer.value) {
        clearInterval(autoRefreshTimer.value)
        autoRefreshTimer.value = null
      }
      window.removeEventListener('resize', handleResize)
      if (statusChartInstance) statusChartInstance.dispose()
      if (serviceChartInstance) serviceChartInstance.dispose()
      if (trendChartInstance) trendChartInstance.dispose()
    })

    return {
      loading,
      activeTab,
      userDetailsVisible,
      cleanupDialogVisible,
      cleanupLoading,
      stats,
      pendingUsers,
      confirmedUsers,
      currentUserDetails,
      cleanupForm,
      // 日志相关
      userLogs,
      logsLoading,
      autoRefresh,
      refreshData,
      viewUserDetails,
      removeUser,
      cleanupExpiredRequests,
      showCleanupDialog,
      exportData,
      handleTabClick,
      formatDateTime,
      formatWaitingTime,
      getServiceTagType,
      getWaitingTimeTagType,
      getStatusTagType,
      getStatusText,
      // 日志方法
      loadUserLogs,
      refreshLogs,
      toggleAutoRefresh,
      // 自动刷新相关
      silentRefreshData,
      // Dashboard相关
      dashboardData,
      statusChart,
      serviceChart,
      trendChart,
      getDashboardData,
      formatUpdateTime
    }
  }
}
</script>

<style scoped>
.queue-management {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.header p {
  color: #7f8c8d;
  font-size: 16px;
}

.stats-section {
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stat-icon.confirmed {
  background: linear-gradient(135deg, #27ae60, #2ecc71);
}

.stat-icon.total {
  background: linear-gradient(135deg, #3498db, #2980b9);
}

.stat-icon.time {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 5px;
}

.actions-section {
  margin-bottom: 30px;
  text-align: center;
}

.actions-section .el-button {
  margin: 0 10px;
}


/* Dashboard样式 */
.dashboard-content {
  padding: 20px 0;
}

.overview-cards {
  margin-bottom: 30px;
}

.overview-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-5px);
}

.overview-card .card-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.overview-card .card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.overview-card .card-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.overview-card .card-icon.pending {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.overview-card .card-icon.confirmed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.overview-card .card-icon.success {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.overview-card .card-info {
  flex: 1;
}

.overview-card .card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.overview-card .card-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chart-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.chart-container {
  height: 300px;
  padding: 10px 0;
}

.chart {
  width: 100%;
  height: 100%;
}

.trend-chart {
  height: 350px;
}

.update-time {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .actions-section .el-button {
    margin: 5px;
  }
  
  .overview-cards .el-col {
    margin-bottom: 15px;
  }
  
  .charts-section .el-col {
    margin-bottom: 20px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .trend-chart {
    height: 300px;
  }
}

.statistics-content {
  padding: 20px 0;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.auto-refresh-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.service-stats {
  padding: 10px 0;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.service-item:last-child {
  border-bottom: none;
}

.service-name {
  font-weight: 500;
  color: #2c3e50;
}

.service-counts {
  display: flex;
  gap: 15px;
}

.pending-count {
  color: #f39c12;
  font-size: 14px;
}

.confirmed-count {
  color: #27ae60;
  font-size: 14px;
}

.performance-stats {
  padding: 10px 0;
}

.performance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.performance-item:last-child {
  border-bottom: none;
}

.performance-label {
  color: #7f8c8d;
  font-size: 14px;
}

.performance-value {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.user-details {
  padding: 20px 0;
}

.cleanup-content {
  padding: 20px 0;
}

.cleanup-content p {
  color: #7f8c8d;
  margin-bottom: 20px;
}

/* 日志相关样式 */
.logs-section {
  margin-top: 20px;
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.logs-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 500;
}

.logs-actions {
  display: flex;
  gap: 8px;
}

.logs-content {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.logs-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
  color: #909399;
  font-size: 14px;
}

.logs-loading .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.logs-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
  color: #909399;
  font-size: 14px;
}

.logs-table-container {
  background: #fff;
}

.logs-table {
  font-size: 13px;
}

.logs-table .el-table__row {
  height: 32px;
}

.logs-table .el-table__cell {
  padding: 4px 8px;
  border-bottom: 1px solid #f0f0f0;
}

.log-row {
  display: flex;
  align-items: center;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  line-height: 1.4;
}

.log-index {
  display: inline-block;
  width: 30px;
  color: #909399;
  font-size: 12px;
  text-align: right;
  margin-right: 8px;
  flex-shrink: 0;
}

.log-text {
  flex: 1;
  word-break: break-all;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .queue-management {
    padding: 10px;
  }
  
  .stats-section .el-col {
    margin-bottom: 15px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .actions-section .el-button {
    margin: 5px;
    width: 100%;
  }
  
  .logs-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .logs-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .logs-actions .el-button {
    flex: 1;
  }
  
  .logs-content {
    max-height: 300px;
  }
  
  .log-item {
    font-size: 12px;
    padding: 6px 10px;
  }
}
</style>
